package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BallotActivity;
import com.jjwxc.jwjskandriod.activity.RechargeCoinActivity;
import com.jjwxc.jwjskandriod.activity.RegisterActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.GifListResponse;
import com.jjwxc.jwjskandriod.model.GiftRankResponse;
import com.jjwxc.jwjskandriod.model.LatestGiftResponse;
import com.jjwxc.jwjskandriod.model.SendGifeResponse;
import com.jjwxc.jwjskandriod.model.UserBalanceResponse;
import com.jjwxc.jwjskandriod.my.data.UserInfoBg;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BollotBombPop {
    private int mBalance;

    @SuppressLint({"ClickableViewAccessibility", "SetTextI18n"})
    public BollotBombPop(View v, Context context, String bookId, PopReturnListener popReturnListener) {
        View view = LayoutInflater.from(context).inflate(R.layout.ballot_buy_pop, null, false);
        LinearLayout back_ll = view.findViewById(R.id.back_ll);
        ImageView img_add = view.findViewById(R.id.img_add);
        ImageView img_sub = view.findViewById(R.id.img_sub);
        TextView tv_num = view.findViewById(R.id.tv_num_buy);
        TextView tv_price = view.findViewById(R.id.tv_price);
        TextView tv_balance = view.findViewById(R.id.tv_balance);
        TextView tv_pay = view.findViewById(R.id.tv_pay);
        TextView tv_paiming = view.findViewById(R.id.tv_paiming);
        List<ImageView> mImageViewList = new ArrayList<>();
        mImageViewList.add(view.findViewById(R.id.img_one));
        mImageViewList.add(view.findViewById(R.id.img_two));
        mImageViewList.add(view.findViewById(R.id.img_three));
        mImageViewList.add(view.findViewById(R.id.img_four));
        mImageViewList.add(view.findViewById(R.id.img_five));

        TextView tv_name_one = view.findViewById(R.id.tv_name_one);
        TextView tv_name_two = view.findViewById(R.id.tv_name_two);
        TextView tv_name_three = view.findViewById(R.id.tv_name_three);
        TextView tv_name_four = view.findViewById(R.id.tv_name_four);
        TextView tv_name_five = view.findViewById(R.id.tv_name_five);

        TextView tv_num_one = view.findViewById(R.id.tv_num_one);
        TextView tv_num_two = view.findViewById(R.id.tv_num_two);
        TextView tv_num_three = view.findViewById(R.id.tv_num_three);
        TextView tv_num_four = view.findViewById(R.id.tv_num_four);
        TextView tv_num_five = view.findViewById(R.id.tv_num_five);

        TextView tv_username_one = view.findViewById(R.id.tv_username_one);
        TextView tv_username_two = view.findViewById(R.id.tv_username_two);
        TextView tv_username_three = view.findViewById(R.id.tv_username_three);

        ImageView img_head_one = view.findViewById(R.id.img_head_one);
        ImageView img_head_two = view.findViewById(R.id.img_head_two);
        ImageView img_head_three = view.findViewById(R.id.img_head_three);


        LinearLayout ll_dm_one = view.findViewById(R.id.ll_dm_one);
        ImageView img_dm_one = view.findViewById(R.id.img_dm_one);
        TextView tv_dm_user = view.findViewById(R.id.tv_dm_user);
        TextView tv_dm_num = view.findViewById(R.id.tv_dm_num);

        LinearLayout ll_dm_two = view.findViewById(R.id.ll_dm_two);
        ImageView img_dm_two = view.findViewById(R.id.img_dm_two);
        TextView tv_dm_user_two = view.findViewById(R.id.tv_dm_user_two);
        TextView tv_dm_num_two = view.findViewById(R.id.tv_dm_num_two);

        //1.構造一個PopupWindow，參數依次是加載的 View，寬高
        int height = context.getResources().getDisplayMetrics().heightPixels;// 屏幕的高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, height + getStatusBarHeight(view.getContext()), true);

        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题

        popWindow.setTouchable(true);
        popWindow.setClippingEnabled(false);
        popWindow.setTouchInterceptor((v12, event) -> {
            return false;
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效
        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        Map<String, Integer> num = new HashMap<>();
        num.put("num", 1);
        Map<String, String> map = new HashMap<>();


        img_add.setOnClickListener(v14 -> {
            num.put("num", num.get("num") + 1);
            tv_num.setText(num.get("num") + "");
            int price = Integer.parseInt(map.get("price")) * num.get("num");
            tv_price.setText("支付" + price + "完结币");
        });
        img_sub.setOnClickListener(v15 -> {
            if (num.get("num") > 1) {
                num.put("num", num.get("num") - 1);
                tv_num.setText(num.get("num") + "");
                int price = Integer.parseInt(map.get("price")) * num.get("num");
                tv_price.setText("支付" + price + "完结币");
            }

        });
        //添加余额信息
        getBalance(context, tv_balance);

        new FFNetWork().post(Url.giftList, null, new FFNetWorkCallBack<GifListResponse>() {
            @Override
            public void onSuccess(GifListResponse response) {
                if (response.getCode() == 200) {

                    List<GifListResponse.DataBean> list = response.getData();
                    map.put("price", list.get(0).getPrice() + "");
                    map.put("giftId", list.get(0).getGiftId());
                    tv_num.setText(num.get("num") + "");
                    tv_price.setText("支付" + list.get(0).getPrice() + "完结币");
                    for (int i = 0; i < mImageViewList.size(); i++) {
                        if (i == 0) {
                            map.put("price", list.get(i).getPrice() + "");
                            map.put("giftId", list.get(i).getGiftId());
                            mImageViewList.get(i).setBackgroundResource(R.drawable.buy_pop_select_ture);
                        } else {
                            mImageViewList.get(i).setBackgroundResource(R.drawable.buy_pop_select_false);
                        }
                    }
                    for (int i = 0; i < mImageViewList.size(); i++) {
                        int finalI = i;
                        mImageViewList.get(i).setOnClickListener(v13 -> {
                            for (int j = 0; j < mImageViewList.size(); j++) {
                                if (finalI == j) {
                                    map.put("price", list.get(j).getPrice() + "");
                                    map.put("num", j + "");
                                    map.put("giftId", list.get(j).getGiftId());
                                    tv_price.setText("支付" + list.get(j).getPrice() + "完结币");
                                    mImageViewList.get(j).setBackgroundResource(R.drawable.buy_pop_select_ture);
                                } else {
                                    mImageViewList.get(j).setBackgroundResource(R.drawable.buy_pop_select_false);
                                }
                            }

                        });
                    }
                    tv_name_one.setText(list.get(0).getName());
                    tv_num_one.setText(list.get(0).getPrice() + "完结币");

                    tv_name_two.setText(list.get(1).getName());
                    tv_num_two.setText(list.get(1).getPrice() + "完结币");

                    tv_name_three.setText(list.get(2).getName());
                    tv_num_three.setText(list.get(2).getPrice() + "完结币");

                    tv_name_four.setText(list.get(3).getName());
                    tv_num_four.setText(list.get(3).getPrice() + "完结币");

                    tv_name_five.setText(list.get(4).getName());
                    tv_num_five.setText(list.get(4).getPrice() + "完结币");

                }

            }

            @Override
            public boolean onFail(GifListResponse response) {
                return false;
            }
        }, GifListResponse.class);
        //获取排行榜
        listBookGiftRank(context, bookId, tv_username_one, tv_username_two,
                tv_username_three, img_head_one, img_head_two,
                img_head_three, ll_dm_one, img_dm_one,
                tv_dm_user, tv_dm_num, ll_dm_two, img_dm_two,
                tv_dm_user_two, tv_dm_num_two, tv_paiming);

        tv_pay.setOnClickListener(v16 -> {
            int price = Integer.parseInt(map.get("price")) * num.get("num");
            if (mBalance >= price) {
                new FFNetWork().post(Url.sendGift, "", new FFNetWorkCallBack<SendGifeResponse>() {
                    @Override
                    public void onSuccess(SendGifeResponse response) {
                        if (response.getCode() == 200) {
                            //刷新余额
                            mBalance = response.getData().getBalance();
                            tv_balance.setText("余额" + mBalance + "完结币");
                            popReturnListener.onValueClick(response.getData().getRank() + "");
                            //获取排行榜
                            listBookGiftRank(context, bookId, tv_username_one, tv_username_two,
                                    tv_username_three, img_head_one, img_head_two,
                                    img_head_three, ll_dm_one, img_dm_one,
                                    tv_dm_user, tv_dm_num, ll_dm_two, img_dm_two,
                                    tv_dm_user_two, tv_dm_num_two, tv_paiming);
                            if (map.get("num").equals("0")) {
                                MobclickAgent.onEvent(context, UMConstant.Event_Reader_Gift_Dilei);
                            } else if (map.get("num").equals("1")) {
                                MobclickAgent.onEvent(context, UMConstant.Event_Reader_Gift_Shouliudan);
                            } else if (map.get("num").equals("2")) {
                                MobclickAgent.onEvent(context, UMConstant.Event_Reader_Gift_Huojianpao);
                            } else if (map.get("num").equals("3")) {
                                MobclickAgent.onEvent(context, UMConstant.Event_Reader_Gift_Zadan);
                            } else if (map.get("num").equals("4")) {
                                MobclickAgent.onEvent(context, UMConstant.Event_Reader_Gift_Yulei);
                            }

                        }

                    }

                    @Override
                    public boolean onFail(SendGifeResponse response) {
                        return false;
                    }
                }, SendGifeResponse.class, "{\"giftId\":\"" + map.get("giftId") + "\",\"count\":" + num.get("num") + ",\"bookId\":\"" + bookId + "\"}");

            } else {
                FFApplication.showToast("余额不足");
                Intent intent = new Intent(context, RechargeCoinActivity.class);
                context.startActivity(intent);
            }
        });
        tv_paiming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BallotActivity.class);
                intent.putExtra("bookId", bookId);
                context.startActivity(intent);
            }
        });
        //设置 popupWindow 里的按钮的事件
        back_ll.setOnClickListener(v1 -> popWindow.dismiss());

    }

    private void listBookGiftRank(Context context, String bookId, TextView tv_username_one, TextView tv_username_two,
                                  TextView tv_username_three, ImageView img_head_one, ImageView img_head_two,
                                  ImageView img_head_three, LinearLayout ll_dm_one, ImageView img_dm_one,
                                  TextView tv_dm_user, TextView tv_dm_num, LinearLayout ll_dm_two, ImageView img_dm_two,
                                  TextView tv_dm_user_two, TextView tv_dm_num_two, TextView tv_paiming) {
        new FFNetWork().post(Url.listBookGiftRank, null, new FFNetWorkCallBack<GiftRankResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(GiftRankResponse response) {
                if (response.getCode() == 200) {
                    List<GiftRankResponse.DataBean.RanksBean> list = response.getData().getRanks();
                    tv_paiming.setText("霸王票我的排名" + response.getData().getUserRank() + "名 >");
                    if (list.size() == 1) {
                        if (StUtils.isEmpty(list.get(0).getUserImg())) {
                            img_head_one.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_one, list.get(0).getUserImg());

                            setImgHead(0, list.get(0).getUserImg());
                        }
                        tv_username_one.setText(list.get(0).getUsername());
                    } else if (list.size() == 2) {
                        if (StUtils.isEmpty(list.get(0).getUserImg())) {
                            img_head_one.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_one, list.get(0).getUserImg());

                            setImgHead(0, list.get(0).getUserImg());
                        }
                        if (StUtils.isEmpty(list.get(1).getUserImg())) {
                            img_head_two.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_two, list.get(1).getUserImg());

                            setImgHead(1, list.get(1).getUserImg());
                        }
                        tv_username_one.setText(list.get(0).getUsername());
                        tv_username_two.setText(list.get(1).getUsername());

                    } else if (list.size() >= 3) {
                        if (StUtils.isEmpty(list.get(0).getUserImg())) {
                            img_head_one.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_one, list.get(0).getUserImg());

                            setImgHead(0, list.get(0).getUserImg());
                        }
                        if (StUtils.isEmpty(list.get(1).getUserImg())) {
                            img_head_two.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_two, list.get(1).getUserImg());

                            setImgHead(1, list.get(1).getUserImg());
                        }
                        if (StUtils.isEmpty(list.get(2).getUserImg())) {
                            img_head_three.setImageResource(R.mipmap.icon_head_default);
                        } else {
//                            FFImageLoader.loadCircleImage(context, img_head_three, list.get(2).getUserImg());

                            setImgHead(2, list.get(2).getUserImg());
                        }

                        tv_username_one.setText(list.get(0).getUsername());
                        tv_username_two.setText(list.get(1).getUsername());
                        tv_username_three.setText(list.get(2).getUsername());
                    }
                }

            }

            /**
             * 设置头像
             * @param type
             * @param userImg
             */
            private void setImgHead(int type, String userImg) {
                int index = Arrays.binarySearch(UserInfoBg.INSTANCE.getUSER_ICON(), userImg);

                if (index >= 0) {
                    if (type == 0) {
                        img_head_one.setImageResource(UserInfoBg.INSTANCE.getUSER_ICON_RID()[index]);
                    }

                    if (type == 1) {
                        img_head_two.setImageResource(UserInfoBg.INSTANCE.getUSER_ICON_RID()[index]);
                    }

                    if (type == 2) {
                        img_head_three.setImageResource(UserInfoBg.INSTANCE.getUSER_ICON_RID()[index]);
                    }
                }
            }

            @Override
            public boolean onFail(GiftRankResponse response) {
                return false;
            }
        }, GiftRankResponse.class, "{\"offset\":0,\"limit\":3,\"bookId\":\"" + bookId + "\"}");
        new FFNetWork().post(Url.listBookLatestGift, null, new FFNetWorkCallBack<LatestGiftResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(LatestGiftResponse response) {
                if (response.getCode() == 200 && response.getData().size() > 0) {
                    if (response.getData().size() == 1) {
                        ll_dm_two.setVisibility(View.VISIBLE);
                        FFImageLoader.loadCircleImage(context, img_dm_two, response.getData().get(0).getUserImg());
                        tv_dm_user_two.setText(response.getData().get(0).getUsername());
                        tv_dm_num_two.setText("赠送了" + response.getData().get(0).getGiftName() + "X" + response.getData().get(0).getGiftCount());
                    } else if (response.getData().size() == 2) {

                        ll_dm_two.setVisibility(View.VISIBLE);
                        FFImageLoader.loadCircleImage(context, img_dm_two, response.getData().get(0).getUserImg());
                        tv_dm_user_two.setText(response.getData().get(0).getUsername());
                        tv_dm_num_two.setText("赠送了" + response.getData().get(0).getGiftName() + "X" + response.getData().get(0).getGiftCount());

                        ll_dm_one.setVisibility(View.VISIBLE);
                        FFImageLoader.loadCircleImage(context, img_dm_one, response.getData().get(1).getUserImg());
                        tv_dm_user.setText(response.getData().get(1).getUsername());
                        tv_dm_num.setText("赠送了" + response.getData().get(1).getGiftName() + "X" + response.getData().get(1).getGiftCount());

                    }
                } else {
                    ll_dm_one.setVisibility(View.GONE);
                    ll_dm_two.setVisibility(View.GONE);
                }

            }

            @Override
            public boolean onFail(LatestGiftResponse response) {
                return false;
            }
        }, LatestGiftResponse.class, "{\"bookId\":\"" + bookId + "\"}");
    }

    private void getBalance(Context context, TextView tv_balance) {

        new FFNetWork().post(Url.balance, null, new FFNetWorkCallBack<UserBalanceResponse>() {
            @Override
            public void onSuccess(UserBalanceResponse response) {
                if (response.getCode() == 200) {
                    mBalance = response.getData().getBalance();
                    tv_balance.setText("余额" + mBalance + "完结币");
                }

            }

            @Override
            public boolean onFail(UserBalanceResponse response) {
                return false;
            }
        }, UserBalanceResponse.class);


    }

    public interface PopReturnListener {
        void onValueClick(String value);
    }

    /**
     * 獲取狀態欄高度
     *
     * @param context context
     * @return 狀態欄高度
     */
    public int getStatusBarHeight(Context context) {
        // 獲得狀態欄高度
        @SuppressLint("InternalInsetResource")
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

}
